package com.ophiux.config;

import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;

/**
 * @desc: 文档操作
 * @author: hhl
 * @date：2023/12/23 22:02
 */
@SpringBootTest
public class DocumentTest {


    private RestHighLevelClient client;



    @Test
    void testAddDocument() throws IOException {
        //根据id，查询数据库
        //转化为文档类型


        //准备Request对象
        IndexRequest request = new IndexRequest("hhlIndex").id("");

        //JSON文档
        request.source("", XContentType.JSON);

        //发送请求
        client.index(request, RequestOptions.DEFAULT);
    }


    @Test
    void testUpdate() throws IOException {
        UpdateRequest request = new UpdateRequest();

        request.doc(
                "info","程序员写java5"
        );

        client.update(request,RequestOptions.DEFAULT);
    }


    @Test
    void delete() throws IOException {
        DeleteRequest request = new DeleteRequest("hhlIndex","1");

        client.delete(request,RequestOptions.DEFAULT);
    }

    @Test
    void testBulkRequest() throws IOException {
        //从数据库查询list,在将list对象转为文档对象，


        //批量查询数据
        BulkRequest bulkRequest = new BulkRequest();

        //准备多个新增的request
        bulkRequest.add(new IndexRequest("hhlIndex").id("1").source("json",XContentType.JSON));
        bulkRequest.add(new IndexRequest("hhlIndex").id("2").source("json",XContentType.JSON));
        bulkRequest.add(new IndexRequest("hhlIndex").id("3").source("json",XContentType.JSON));


        client.bulk(bulkRequest, RequestOptions.DEFAULT);
    }




    @BeforeEach
    public void init(){
        this.client = new RestHighLevelClient(RestClient.builder(
                new HttpHost("http://192.168.30.128", 9200)
        ));
    }
    @AfterEach
    public void close() throws IOException {
        this.client.close();
    }
}
